<?php

namespace mpend\modules\passport\models;

use Yii;
use mpend\models\User;
use common\models\user\UserAuthent;
use common\models\user\UserAuthentData;
use common\validators\MobileValidator;
use common\validators\IdcardValidator;
use common\helpers\ArrayHelper;

class RegisterForm extends \common\base\Model {

    /**
     * @var string 
     */
    public $user_id;

    /**
     * @var string 真实姓名
     */
    public $username;

    /**
     * @var string 真实姓名
     */
    public $password;

    /**
     * @var string 真实姓名
     */
    public $realname;

    /**
     * @var string 身份证号
     */
    public $idcardno;

    /**
     * @var string 人像照片
     */
    public $photo;

    /**
     * @var string 民族
     */
    public $nation;

    /**
     * @var string 政治面貌
     */
    public $politic;

    /**
     * @var string 学历
     */
    public $education;

    /**
     * @var string 毕业院校
     */
    public $school;

    /**
     * @var string 参加工作日期
     */
    public $workdate;

    /**
     * @var string 工作单位
     */
    public $company;

    /**
     * @var string 注册类型
     */
    public $type;

    /**
     * @var string 研究领域
     */
    public $scope;

    /**
     * @var string 工作简历
     */
    public $resume;

    /**
     * @var string 手机号
     */
    public $mobile;

    /**
     * @var string 邮箱
     */
    public $email;

    /**
     * @var User|null 用户信息
     */
    private $_user;

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['user_id'], 'integer'],
            [['user_id', 'username', 'password', 'realname', 'idcardno', 'nation', 'politic', 'education', 'school', 'workdate', 'company', 'type', 'resume', 'mobile'], 'required'],
            [['username'], 'string', 'max' => 20],
            [['password'], 'string', 'min' => 6, 'max' => 16],
            ['password', 'match', 'pattern' => static::passwordPattern(), 'message' => '密码过于简单需6~16位字符，建议字母数字符号组合'],
            [['realname'], 'string', 'max' => 8],
            [['idcardno'], 'string', 'max' => 18],
            [['nation', 'politic', 'education', 'school', 'company', 'type', 'email'], 'string', 'max' => 50],
            [['photo'], 'string', 'max' => 255],
            [['workdate'], 'string', 'max' => 20],
            [['mobile'], 'string', 'max' => 11],
            [['user_id'], 'validateUser'],
            [['username'], 'validateUsername'],
            [['resume'], 'string'],
            [['mobile'], 'validateMobile'],
            [['idcardno'], 'validateIdcardno'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels() {
        return [
            'username' => '用户名',
            'password' => '密码',
            'realname' => '姓名',
            'idcardno' => '证件号码',
            'photo' => '个人照片',
            'passport_front' => '证件照片',
            'district' => '地区',
            'address' => '详细地址',
        ];
    }

    /**
     * 校验密码是否正确
     * @param string $attribute the attribute currently being validated
     * @param array $params the additional name-value pairs given in the rule
     */
    protected static function passwordPattern() {
        return ArrayHelper::getValue(Yii::$app->params, 'format_pattern.password', '/(.*){6,16}/i');
    }

    /**
     * 校验当前用户
     */
    public function validateUser($attribute) {
        if ($this->hasErrors()) {
            return;
        }
        $userClass = Yii::$app->user->identityClass;
        $user = $userClass::findOne($this->$attribute);
        if (!$user) {
            return $this->addError($attribute, '注册失败，用户信息状态异常');
        }
        $this->_user = $user;
    }

    /**
     * 校验唯一用户名
     */
    public function validateUsername($attribute) {
        if ($this->hasErrors()) {
            return;
        }
        /* @var $userClass \common\models\user\User */
        $userClass = Yii::$app->user->identityClass;
        $user = $userClass::find()->andWhere([
            'and',
            ['username' => $this->$attribute],
            ['!=', 'id', $this->user_id],
        ])->one();
        if ($user) {
            return $this->addError($attribute, '当前用户名已被占用');
        }
    }

    /**
     * 校验唯一手机号
     */
    public function validateMobile($attribute) {
        if ($this->hasErrors()) {
            return;
        }
        $validator = new MobileValidator();
        if (!$validator->validate($this->$attribute)) {
            return $this->addError($attribute, '手机号码格式不正确，请输入正确的手机号码！');
        }
    }

    /**
     * 校验唯一身份证号
     */
    public function validateIdcardno($attribute) {
        if ($this->hasErrors()) {
            return;
        }
        $validator = new IdcardValidator();
        if (!$validator->validate($this->$attribute)) {
            return $this->addError($attribute, '身份证号码不正确，请输入正确的身份证号码！');
        }
        $authent = UserAuthent::findByIdcardno($this->$attribute);
        if (!$authent) {
            return;
        }
        if ($authent->status >= 0 && $authent->user_id != $this->user_id) {
            return $this->addError($attribute, '证件号已被占用，请检查输入的信息是否正确');
        }
    }

    /**
     * @return User
     */
    public function getUser() {
        return $this->_user;
    }

    /**
     * 保存动态信息（发布&修改）
     * @param [type] $data
     * @return void
     */
    public function save() {
        if (!$this->validate()) {
            return $this->dumpError('');
        }
        $user = $this->getUser();
        if (!$user->mobile) {
            $user->setMobile($this->mobile);
        }
        $user->username = $this->username;
        $user->nickname = $this->realname;
        $user->setPassword($this->password);
        $user->email = $this->email;
        $user->status = $user::STATUS_ACTIVE;
        $userMeta = $user->meta;

        /* @var $model \common\models\user\UserAuthent */
        $model = UserAuthent::findOrNew([
            'user_id' => $user->id
        ]);
        $types = [
            0 => '科技工作特派员',
            1 => '科技创新特派员'
        ];
        $type = (int) array_search($this->type, $types);
        $userMeta->signature = $type;
        $model->setAttributes([
            'realname' => $this->realname,
            'photo' => $this->photo,
            'type' => $type,
        ]);
        $model->setIdcardno($this->idcardno);
        $user->gender = $model->gender;
        $userMeta->gender = $model->gender;

        $authData = $model->authData;
        if (!$authData) {
            $authData = UserAuthentData::findOrNew([
                'user_id' => $user->id,
            ]);
        }
        $workdate = date('Y-m-d', strtotime($this->workdate));
        $authData->setAttributes([
            'scope' => $this->scope,
            'nation' => $this->nation,
            'politic' => $this->politic,
            'education' => $this->education,
            'school' => $this->school,
            'workdate' => $workdate,
            'company' => $this->company,
            'resume' => $this->resume,
        ]);

        //开启事务
        $transaction = Yii::$app->db->beginTransaction();
        try {
            if (!$user->save()) {
                Yii::error($user->getErrorMsg());
                return $this->dumpError('用户信息保存失败');
            }
            if (!$model->save()) {
                return $this->dumpError('认证信息保存失败');
            }
            $authData->authent_id = $model->id;
            if (!$authData->save()) {
                return $this->dumpError('资料信息保存失败');
            }
            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            $this->dumpError($e->getMessage());
        }
        return $user;
    }

}
